package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Version;
import com.example.mapper.DownloadLinkMapper;
import com.example.mapper.PhoneMapper;
import com.example.mapper.VersionMapper;
import com.example.service.VersionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 固件版本Service实现类
 */
@Service
public class VersionServiceImpl implements VersionService {
    
    @Resource
    private VersionMapper versionMapper;
    
    @Resource
    private PhoneMapper phoneMapper;
    
    @Resource
    private DownloadLinkMapper downloadLinkMapper;

    /**
     * 分页查询固件版本
     */
    @Override
    public PageInfo<Version> page(Integer pageNum, Integer pageSize, Integer phoneId, String region, String version) {
        PageHelper.startPage(pageNum, pageSize);
        List<Version> list = versionMapper.list(phoneId, region, version);
        return new PageInfo<>(list);
    }

    /**
     * 根据ID查询固件版本
     */
    @Override
    public Version getById(Integer id) {
        return versionMapper.getById(id);
    }

    /**
     * 新增固件版本
     */
    @Override
    @Transactional
    public void add(Version version) {
        version.setCreateTime(DateUtil.now());
        versionMapper.insert(version);
        
        // 更新手机设备的固件数量
        updatePhoneFirmwareCount(version.getPhoneId());
    }

    /**
     * 更新固件版本
     */
    @Override
    public void update(Version version) {
        versionMapper.update(version);
    }

    /**
     * 删除固件版本
     */
    @Override
    @Transactional
    public void delete(Integer id) {
        Version version = versionMapper.getById(id);
        if (version != null) {
            // 先删除关联的下载链接
            downloadLinkMapper.deleteByVersionId(id);
            // 再删除固件版本
            versionMapper.deleteById(id);
            // 更新手机设备的固件数量
            updatePhoneFirmwareCount(version.getPhoneId());
        }
    }
    
    /**
     * 更新手机设备的固件数量
     */
    private void updatePhoneFirmwareCount(Integer phoneId) {
        Integer count = versionMapper.countByPhoneId(phoneId);
        phoneMapper.updateFirmwareCount(phoneId, count);
    }
} 